package com.qf.dao.Impl;

import com.alibaba.fastjson.JSON;
import com.qf.dao.EmsDao;
import com.qf.pojo.Emp;
import com.qf.utils.Dbutils;
import com.qf.utils.Sqlutil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class EmpDaoImpl implements EmsDao {
    private  static QueryRunner queryRunner = new QueryRunner();
    @Override
    public int add(Emp emp) {
        String sql = Sqlutil.getSqlL("add");
        Object[] a = {emp.getName(),emp.getSalary(),emp.getAge()};
        try {
            int update = queryRunner.update(Dbutils.getConnection(), sql, a);
            return update;
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+"添加异常");
        }
    }

    @Override
    public int delete(int id) {
       String sql = Sqlutil.getSqlL("delete");
        try {
            int update = queryRunner.update(Dbutils.getConnection(), sql, id);
            return update;
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+"删除异常");
        }
    }

    @Override
    public int update(Emp emp) {
        String sql = Sqlutil.getSqlL("update");
        Object[] a = {emp.getName(),emp.getSalary(),emp.getAge(),emp.getId()};
        try {
            int update = queryRunner.update(Dbutils.getConnection(), sql, a);
            return update;
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+"修改异常");
        }
    }

    @Override
    public Emp select(int id) {
        String sql = Sqlutil.getSqlL("select");
        try {
            Emp query = queryRunner.query(Dbutils.getConnection(), sql, new BeanHandler<>(Emp.class),id);
            return query;
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+"查询单个异常");
        }
    }

    @Override
    public List<Emp> selectAll() {
        String sql = Sqlutil.getSqlL("selectAll");
        try {
            List<Emp> query = queryRunner.query(Dbutils.getConnection(), sql, new BeanListHandler<>(Emp.class));
            return query;
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+"查询所有异常");
        }
    }

    @Override
    public List<Emp> fenye(int pyl, int pageSize) {
        String sqlL = Sqlutil.getSqlL("pyl");
        try {
            List<Emp> query = queryRunner.query(Dbutils.getConnection(), sqlL, new BeanListHandler<>(Emp.class),pyl,pageSize);
            return query;
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+"分页异常");
        }
    }
}
